package server;

import container.Context;
import container.Host;
import container.Mapper;
import container.Wrapper;

import java.io.OutputStream;
import java.net.Socket;
import java.util.List;
import java.util.stream.Collectors;

public class RequestProccesor implements Runnable {

    private Socket accept;
    private Mapper mapper;

    public Socket getAccept() {
        return accept;
    }

    public void setAccept(Socket accept) {
        this.accept = accept;
    }

    public Mapper getServletMap() {
        return mapper;
    }

    public void setServletMap(Mapper mapper) {
        this.mapper = mapper;
    }

    public RequestProccesor() {
    }

    public RequestProccesor(Socket accept, Mapper httpServletMap) {
        this.accept = accept;
        this.mapper = httpServletMap;
    }

    @Override
    public void run()  {
        try {
            OutputStream outputStream = accept.getOutputStream();

            // 封装Request对象和Response对象
            Request request = new Request(accept.getInputStream());
            Response response = new Response(accept.getOutputStream());

//            if(mapper.get(request.getUrl()) == null) {
//                response.outputHtml(request.getUrl());
//            } else {
//                mapper.get(request.getUrl()).service(request, response);
//            }
            String url = request.getUrl();
            if (url == null) url = "/";
            url =  !url.startsWith("/") ? "/" + url : url;

            // 如果请求/, 则直接返回test.html
            if(request.getUrl() == null || request.getUrl().equalsIgnoreCase("/")) {
                response.outputHtml("/test.html");
            } else {

                String[] split = url.split("/");
                // 当split为空时， 键为 “/"
                String host = "/" + split[1];
                // 获取主机目录 和 访问路径
                String pathStr = "";
                if(split.length == 1) {
                    pathStr = "/";
                } else {
                    pathStr = url.substring(host.length(), url.length());
                }
                if (pathStr.contains("?")) {
                    pathStr = pathStr.substring(host.length());
                }
                pathStr = pathStr.startsWith("/") ? pathStr : "/" + pathStr;
                final String path = pathStr;

                // 标记路径对应的资源是否存在
                boolean isExist = true;
                List<Host> hosts = mapper.getHosts();
                if (hosts.size() > 0) {
                    // 过滤符合请求路径的host
                    List<Host> availableHosts = hosts.stream()
                            .filter(h -> h.getStrValue().equals(host) || ("/" + h.getStrValue()).equals(host))
                            .collect(Collectors.toList());
                    if (availableHosts.size() > 0) {
                        // 请求的目标主机
                        Host targetHost = availableHosts.get(0);
                        // 过滤符合请求路径的servlet
                        Context context = targetHost.getContext();
                        if (context != null) {
                            // 请求的servlet包装类
                            List<Wrapper> wrappers = context.getWrappers();
                            List<Wrapper> wrapperList = wrappers.stream()
                                    .filter(wrapper -> wrapper.getName().equals(path) || ("/" + wrapper.getName()).equals(path))
                                    .collect(Collectors.toList());
                            if (wrapperList.size() < 1) {
                                // 若没有对应的servlet映射， 则当静态资源处理
                                response.outputHtml(request.getUrl());
                            } else {
                                // 否则， 访问对应的sesrvlet
                                wrapperList.get(0).getValue().
                                        service(request, response);
                            }

                        } else {
                            isExist = false;
                        }
                    } else {
                        isExist = false;
                    }


                } else {
                    isExist = false;
                }

                // 如果未找到资源， 则返回404错误
                if(!isExist) {
                    response.outputHtml(HttpProtocolUtil.getHttpHeader404());
                }
            }

            accept.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String s = "/";
        String s1 = s.substring(1);
//        String[] split = s.split("/a");
//        System.out.println(split.length);
        System.out.println(s1 + "/");
    }
}
